package com.lib.base.utils

import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

class MD5 {

    companion object {
        val DIGITS = charArrayOf(
            '0',
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9',
            'a',
            'b',
            'c',
            'd',
            'e',
            'f',
            'g',
            'h',
            'i',
            'j',
            'k',
            'l',
            'm',
            'n',
            'o',
            'p',
            'q',
            'r',
            's',
            't',
            'u',
            'v',
            'w',
            'x',
            'y',
            'z'
        )

        @Throws(NoSuchAlgorithmException::class)
        fun encode(string: String): String {

            val e = MessageDigest.getInstance("MD5")
            return bytesToHexString(e.digest(string.toByteArray()))

        }

        private fun bytesToHexString(bytes: ByteArray): String {
            val buf = CharArray(bytes.size * 2)
            var c = 0
            var i = 0

            val z = bytes.size
            while (i < z) {
                val b = bytes[i]
                buf[c++] = DIGITS[b.toInt() shr 4 and 15]
                buf[c++] = DIGITS[b.toInt() and 15]
                ++i
            }

            return String(buf)
        }
    }


}